//
//  PartyActivityViewController.m
//  UESTCPioneer
//
//  Created by Sway on 14-3-5.
//  Copyright (c) 2014年 Sway. All rights reserved.
//

#import "PartyActivityViewController.h"
#import "UPTableView.h"
#import "UPTitleCell.h"
#import "UPMainInfoCell.h"
#import "UPFooterCell.h"
#import "LeveyTabBarController.h"
#import "PartyCategoryViewController.h"
#import "PartyCategoryTableViewController.h"

#import "MoodShareViewController.h"

#pragma mark - 颜色
#define kNavigationBarColor [UIColor colorWithRed:192.0/255.0 green:57.0/255.0 blue:43.0/255.0 alpha:1]
#define KSPEColor [UIColor colorWithRed:204.0/255.0 green:204.0/255.0 blue:204.0/255.0 alpha:1]
#define KBtnTextColor [UIColor colorWithRed:119.0/255.0 green:119.0/255.0 blue:119.0/255.0 alpha:1]

#define headWidth1 320

@interface PartyActivityViewController ()<UPFooterCellDelegate>{
    UIView *slideBar;
    UIButton *letfBtn;
    UIButton *rightBtn;
}

@property (nonatomic,strong) NSMutableArray * contentArray;
@property (nonatomic,strong) NSArray * collegeArray;

@end

@implementation PartyActivityViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    UnreadKey=kUnreadPartyNoticeKey;
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    tableViewTopConstraint.constant = 48;
    
    [self addHeadView];
    [self hideTopView];
    /*修改*/
    [dropbtn setTitle:@"最新" forState:UIControlStateNormal];
    /**/
    
#pragma mark 请求数据
    entityName=kPartyActivityNewsEntityName;
    entityMapping=[Mapping PartyActivityMapping];
    /*
     type=getEvent&userId=00100131103&page=1
     */
    requestData=@{@"type":@"getEvent",@"userId":[constant getUserId],@"page":@"1"};
    commentListRequestData=@{@"type":@"getEventComment",@"eventid":@"0"
                             ,@"page":@"1"};
    commentIdKey=@"eventid";
    
    
    /*
     
     ype：请求类型；userId：请求者权限Id；userName：请求者用户名；eventid：活动id（数据库中的序号）；comment：评论的内容（utf-8编码）
     */
    commentWriteRequestData=@{@"type":@"eventComment"
                              ,@"userId":[constant getUserId]
                              ,@"userName":[constant getUserName]
                              ,@"eventid":@"0"
                              ,@"comment":@""};
    commentWriteIdKey=@"eventid";
    commentContentKey=@"comment";
    
    commentListKeyMapping=@{@"commentAuthor":@"userName",@"commentContent":@"commentBody",@"commentDate":@"commentDate"};
    commentFlag = @"PartyActivity";
    [self getCollege];
    
}

#pragma mark -
#pragma mark 添加头部
-(void)addHeadView{
    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 260, 47)];
    headView.backgroundColor = [UIColor clearColor];
    
    UIView *barLine = [[UIView alloc] initWithFrame:CGRectMake(0, 47, 320,1)];
    barLine.backgroundColor = KSPEColor;
    [headView addSubview:barLine];
    
    letfBtn = [self addBtn:CGRectMake(0, 0, 320/2, 47) title:@"组织活动" tag:1 normalColor:kNavigationBarColor];
    [headView addSubview:letfBtn];
    
    rightBtn = [self addBtn:CGRectMake(320/2, 0, 320/2, 47) title:@"体验分享" tag:2 normalColor:KBtnTextColor];
    
    [headView addSubview:rightBtn];
    
    slideBar = [[UIView alloc] initWithFrame:CGRectMake(320/2, 43, 320/2, 4)];
    slideBar.backgroundColor = kNavigationBarColor;
    [headView addSubview:slideBar];
    [self.view addSubview:headView];
    
}



//1.添加按钮
-(UIButton *)addBtn:(CGRect)rect title:(NSString*)title tag:(NSInteger)tag normalColor:(UIColor*)color{
    UIButton *btn = [[UIButton alloc] initWithFrame:rect];
    [btn setTitle:title forState:UIControlStateNormal];
    btn.tag = tag;
    [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    [btn setTitleColor:kNavigationBarColor forState:UIControlStateHighlighted];
    [btn setTitleColor:color forState:UIControlStateNormal];
    return btn;
}
//2.按钮点击
-(void)btnClick:(UIButton*)btn{
    if (btn.tag != 1) {
        MoodShareViewController *shareContr = [[MoodShareViewController alloc] init];
        
        [self.leveyTabBarController removeViewControllerAtIndex:0];
        [self.leveyTabBarController setSelectedIndex:1];
        
        [shareContr willMoveToParentViewController:self.leveyTabBarController];
        [self.leveyTabBarController insertViewController:shareContr  atIndex:0];
        [self.revealSideViewController popViewControllerWithNewCenterController:[constant getCenterController] animated:YES];
        [self.leveyTabBarController setSelectedIndex:0];
        [shareContr didMoveToParentViewController:[constant getCenterController]];
    }
}

//3.滑条动画
-(void)Animation:(int)selelctTag{
    CGRect newFram = slideBar.frame;
    newFram = CGRectMake(selelctTag * 320/2, 43, 320/2, 4);
    [UIView beginAnimations:@"slide" context:nil];
    [UIView setAnimationDuration:0.40];
    [slideBar setFrame:newFram];
    [UIView commitAnimations];
}
#pragma mark -
#pragma mark View appear

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self Animation:0];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.leveyTabBarController.navigationItem setTitle:@"党员活动"];
    /*修改*/
    self.isPartyActivity = YES;
    /**/
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(ScreenTouch)];
    [self.tableView addGestureRecognizer:tapGesture];

//    /*添加20141026*/
//    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(235, 0, 110, 44)];
//    [btn setTitleEdgeInsets:UIEdgeInsetsMake(8, 0, 8, 25)];
//    [btn.titleLabel setTextAlignment:NSTextAlignmentLeft];
//    NSString *title = @"全部";
//    
//    if ([constant getCurrentView] == 2) {
//        title = @"最新";
//    }
//    
//    [btn setTitle:title forState:UIControlStateNormal];
//    btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
//    [btn.titleLabel setFont:[UIFont systemFontOfSize:13.0f]];
//    btn.tintColor = [UIColor whiteColor];
//    [btn addTarget:self action:@selector(dropClicked:) forControlEvents:UIControlEventTouchUpInside];
//    
//    UIImageView *xiala = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"xiala.png"]];
//    xiala.contentMode = UIViewContentModeScaleAspectFit;
//    xiala.frame = CGRectMake(88, 8+9, 12, 12);
//    xiala.tag = 22;
//    [btn addSubview:xiala];
//    
//    dropbtn = btn;
//    UIBarButtonItem *barItem2=[helper BarButtonItemWithUIButton:btn ButtonOrigin:CGPointMake(0, 0) CustomViewSize:CGSizeMake(110, 44)];
//    
//    self.leveyTabBarController.navigationItem.rightBarButtonItem = barItem2;
//    /**/
    [self _initBarButton];
}

-(void)leftMenuClick{
    [self.leveyTabBarController.revealSideViewController pushOldViewControllerOnDirection:PPRevealSideDirectionLeft animated:YES];
}

#pragma  mark  触摸事件
-(BOOL)ScreenTouch{
    if(dropDown == nil) {
        return NO;
    }
    else {
        [dropDown hideDropDown:dropbtn];
        [self rel];
        return YES;
    }
}

-(void)dropList:(id)btn{
    [self dropClicked:btn];
}

- (void)dropClicked:(id)sender {
    NSMutableArray * arr = [[NSMutableArray alloc] init];
    arr = [NSMutableArray arrayWithObjects:@"最新",@"热门",nil];
    [arr addObjectsFromArray:self.contentArray];
    if(dropDown == nil) {
        CGFloat newHeight = 180;
        CGRect newfram = CGRectMake(215, -80, 105, 80);
        dropDown = [[NIDropDown alloc] initDropDown:sender withFram:newfram withHeight:newHeight content:arr forView:self.view];
        dropDown.delegate = self;
    }
    else {
        [dropDown hideDropDown:sender];
        [self rel];
    }
}

#pragma mark - dropDelegate
-(void)niDropDownDelegateMethod:(NIDropDown *)sender ForTitle:(NSString *)title ForIndex:(NSInteger)index{
    if ([title isEqualToString:@"最新"]||[title isEqualToString:@"热门"]) {
        requestData=[RequestData ActivityDataWithTypeName:title];
        [self.tableView beginRefreshing];
    }else{
        NSString * partyNo = [NSString string];
        for (NSDictionary * dic in self.collegeArray) {
            if ([dic[@"partyName"] isEqualToString:title]) {
                partyNo = dic[@"partyNo"];
            }
        }
        requestData=[RequestData CollegeActivityDataWithTypeName:partyNo];
        [self refreshTableView];
    }
    [self rel];
}

-(void)showList{
    
    PartyCategoryViewController * controller = [[PartyCategoryViewController alloc] initWithArray:self.contentArray block:^(NSDictionary *college) {
        
        NSString * title = [NSString stringWithFormat:@"分类:%@",college[@"partyName"]];
        
        [dropbtn setTitle:title forState:UIControlStateNormal];
        
        dropbtn.titleLabel.adjustsFontSizeToFitWidth = YES;
        
        
    }];
    controller.navigationItem.title = @"分类";
    [self.leveyTabBarController.navigationController pushViewController:controller animated:YES];
}

-(void)refreshTableView{
    [PublicMethod ClearEntity:entityName];
    [NetworkCenter RKRequestWithData:requestData EntityName:entityName Mapping:entityMapping SuccessBlock:^(NSArray *resultArray) {
        NSMutableArray *dic = [[NSMutableArray alloc]init];
        if (resultArray.count<=0) {
            [Alert showAlert:@"该学院没有数据"];
        }
        [dic addObjectsFromArray:resultArray];
        tableViewEntitiesArray=[[NSArray alloc]initWithArray:dic];
        
        for (NSInteger i = 0; i < tableViewEntitiesArray.count;i++ ) {
            NewsEntity *entity= tableViewEntitiesArray[i];
            entity.newsBody = [NSString stringWithFormat:@"[%@]\n%@",entity.titleBody,entity.newsBody];
        }
        [self.tableView reloadData];
        PullUpRefreshTimes=0;
    } failure:^(NSError *error) {
        //        NSLog(@"%@ 下拉请求失败",entityName);
        //        NSLog(@"请求错误：error = %@",error.localizedDescription);
        [Alert showAlert:@"网络连接出错!"];
    }];
}

-(void)getCollege{
    self.contentArray = [NSMutableArray array];
    NSDictionary *getCollegeRequestData = @{@"type":@"getCollegeList"};
    [NetworkCenter AFRequestWithData:getCollegeRequestData SuccessBlock:^(AFHTTPRequestOperation *operation, id resultObject) {
        NSArray *dic = [NSJSONSerialization JSONObjectWithData:resultObject options:NSJSONReadingMutableLeaves error:nil];
        for (NSDictionary *d in dic) {
            [self.contentArray addObject:d[@"partyName"]];
        }
        self.collegeArray = [NSMutableArray arrayWithArray:dic];
        //        [self showList];
    } FailureBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        [Alert showAlert:@"获取学院列表错误"];
        return ;
    }];
}

#pragma mark - TableView Delegate
//每个分区的行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 3;
}

//表的分区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return [tableViewEntitiesArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell=[super tableView:tableView cellForRowAtIndexPath:indexPath];
    PartyActivityNewsEntity *entity = tableViewEntitiesArray[indexPath.section];
    if (indexPath.row == 0) {
        //        static NSString *customTitleCellIndentifier = @"CustomTitleCellIndentifier";
        //        UPTitleCell *cell = [tableView dequeueReusableCellWithIdentifier:customTitleCellIndentifier];
        //        if(cell == nil){
        //            cell = [[UPTitleCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:customTitleCellIndentifier];
        //        }
        //        UILabel *title = (UILabel *)[cell.contentView viewWithTag:titleTag];
        //        title.text = @"title";
        //        UILabel *time = (UILabel *)[cell.contentView viewWithTag:timeTag];
        //        time.text = @"time";
        UPTitleCell *cell1 = (UPTitleCell*)cell;
        /*修改*/
        [cell1 setTitle:entity.branch];
        /**/
        return cell1;
    }
    else if (indexPath.row == 1) {
        //        static NSString *customMainCellIndentifier = @"CustomMainCellIndentifier";
        //        UPMainInfoCell *cell2 = [tableView dequeueReusableCellWithIdentifier:customMainCellIndentifier];;
        //        if(cell2 == nil){
        //            cell2 = [[UPMainInfoCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:customMainCellIndentifier];
        //        }
        //        UILabel *words = (UILabel *)[cell2.contentView viewWithTag:wordsTag];
        //        words.text = @"在讨论这部纪录片之前，为了避免现在中文网络江湖盛行的动机论，我先要说明：我和崔永元老师没有个人恩怨，相反，对他的主持功力和以前取得的成绩都非常钦佩。我们也至少有一名共同的好朋友，《读库》的出版人张立宪。";
        UPMainInfoCell *cell2= (UPMainInfoCell*)cell;
        /*修改*/
        [cell2 setNewsBody:entity.newsBody];
        /**/
        return cell2;
    }
    else {
        UPFooterCell *cell3 = (UPFooterCell*)cell;
        //        static NSString *customFooterCellIndentifier = @"CustomFooterCellIndentifier";
        //        UPFooterCell *cell3 = [tableView dequeueReusableCellWithIdentifier:customFooterCellIndentifier];;
        //        if(cell3 == nil){
        //            cell3 = [[UPFooterCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:customFooterCellIndentifier];
        //        }
        //        UIButton *btn1 = (UIButton *)[cell3.contentView viewWithTag:btn1Tag];
        //        UIButton *btn2 = (UIButton *)[cell3.contentView viewWithTag:btn2Tag];
        //        UIButton *btn3 = (UIButton *)[cell3.contentView viewWithTag:btn3Tag];
        //        btn1.hidden = NO;
        cell3.delegate=self;
        cell3.shareButtonEnable=YES;
        
        
        //        NSLog(@"entity.love = %@,indexpath.row= %i",entity.love,indexPath.row);
        if ([entity.love isEqual:@1]) {
            [cell3 setShareButtonImage:[UIImage imageNamed:@"dig2.png"]];
        }else{
            [cell3 setShareButtonImage:[UIImage imageNamed:@"dig.png"]];
        }
        //        [cell3 setShareButtonImage:[UIImage imageNamed:@"dig.png"]];
        [cell3 setShareNum:[entity.count integerValue]];
        //        NSLog(@"dropbtn.titleLabel.text = %@",dropbtn.titleLabel.text);
        if ([dropbtn.titleLabel.text isEqualToString:@"最新"]) {
            cell3.markButtonEnable=YES;
            
            [cell3.markButton setImage:[UIImage imageNamed:@"sign"] forState:UIControlStateNormal];
            [cell3.markButton setImage:[UIImage imageNamed:@"sign_mark"] forState:UIControlStateSelected];
            BOOL signUp= [entity.signUp boolValue];
            [cell3 setMarkButtonStatus:signUp];
        }else if ([dropbtn.titleLabel.text isEqualToString:@"热门"]){
            cell3.markButtonEnable=NO;
        }
        
        //        btn2.hidden = NO;
        //        [btn1 setImage:[UIImage imageNamed:@"sign.png"] forState:UIControlStateNormal];
        //        UIImageView *dig = (UIImageView *)[btn2 viewWithTag:11];
        //        [dig setImage:[UIImage imageNamed:@"dig.png"]];
        //        [btn2 setTitle:@"21" forState:UIControlStateNormal];
        return cell3;
    }
    
}

//修改行高度的位置
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [super tableView:tableView heightForRowAtIndexPath:indexPath];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 5;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    // indexPath.section,根据分组进行更精确的配置
    return 5;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 点赞

/*
 type=clickLove&userId=00100131103&userName=1111&eventid=2
 */


-(void)UPFooterCell:(UPFooterCell *)cell shareButtonPress:(UIButton *)button{
    if (cell.shareButtonRequesting){
        [Alert showAlert:@"您点太快了"];
        return;
    }
    
    //@标识赞正在进行异步请求,防止用户快速点击
    cell.shareButtonRequesting=YES;
    
    PartyActivityNewsEntity *entity  =[PublicMethod entity:kPartyActivityNewsEntityName WithId:cell.theId];
    
    NSDictionary *DiggRequestData = @{
                                      @"type":@"clickLove"
                                      ,@"userId":[constant getUserId]
                                      ,@"userName":[constant getUserName]
                                      ,@"eventId":[NSString stringWithFormat:@"%d",cell.theId]
                                      };
    
    [NetworkCenter AFRequestWithData:DiggRequestData SuccessBlock:^(AFHTTPRequestOperation *operation, id resultObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:resultObject options:NSJSONReadingMutableLeaves error:nil];
        NSString *result =dic[@"result"];
        
        
        if ([result isEqualToString:@"success"]){
            NSInteger count =  [entity.count integerValue];
            //            NSLog(@"******************************************************entity.love=%@",entity.love);
            if ([entity.love integerValue] == 0) {
                entity.love = [NSNumber numberWithInteger:1];
                entity.count=[NSNumber numberWithInteger:++count];
                [cell setShareNum:count];
                [cell setShareButtonImage:[UIImage imageNamed:@"dig2.png"] ];
                [Alert showAlert:@"点赞成功"];
            }else{
                entity.love = [NSNumber numberWithInteger:0];
                NSInteger count =  [entity.count integerValue];
                entity.count=[NSNumber numberWithInteger:--count];
                [cell setShareNum:count];
                [cell setShareButtonImage:[UIImage imageNamed:@"dig.png"]];
                [Alert showAlert:@"取消赞"];
            }
            
            
        }
        else [Alert showAlert:@"点赞错误"];
        cell.shareButtonRequesting=NO;
    } FailureBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        [Alert showAlert:@"点赞错误"];
        cell.shareButtonRequesting=NO;
    }];
}

#pragma mark - 报名


/*
 type=getEvent&userId=00120051300
 
 type：请求类型；userId：用户权限Id；userName：用户名；eventid：要报名的活动序号；signUp：报名请求标志，1为报名，0为取消报名；name：用户的姓名（utf-8编码）
 */

-(void)UPFooterCell:(UPFooterCell *)cell markButtonClick:(UIButton *)button{
    
    
    //    PartyActivityNewsEntity *entity = [PublicMethod entity:kPartyActivityNewsEntityName WithId:cell.theId];
    
    NSInteger signUp = button.selected;
    
    NSDictionary *signUpRequestData = @{
                                        @"type":@"getEvent"
                                        ,@"userId":[constant getUserId]
                                        ,@"userName":[constant getUserName]
                                        ,@"eventid":[NSString stringWithFormat:@"%d",cell.theId]
                                        ,@"signUp":[NSString stringWithFormat:@"%d",signUp]
                                        ,@"name":[constant getName]
                                        };
    
    
    [NetworkCenter AFRequestWithData:signUpRequestData SuccessBlock:^(AFHTTPRequestOperation *operation, id resultObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:resultObject options:NSJSONReadingMutableLeaves error:nil];
        NSString *resultString=dic[@"result"];
        resultString=[resultString substringToIndex:7];
        if ([resultString isEqualToString:@"success"]){
            [Alert showAlert:@"操作成功"];
        }
        else {
            [Alert showAlert:@"操作失败"];
        }
        
    } FailureBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        [Alert showAlert:@"发生错误"];
    }];
    
}





//）type：getEvent  （2）userId：查看着的用户账号
//（3）page：页码
//
//#define testData @{@"type":@"getEvent",@"userId":@"0010013110361",@"page",@"1"}
//#define


@end
